﻿var showdownConverter = new Showdown.converter();

ko.bindingHandlers.markdown = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        var html = showdownConverter.makeHtml(value);

        $(element).html(html);
    }
};

function Article(source) {
    var self = this;

    this.id = '';
    this.source = source;

    this.getTitle = function () {
        return self.source.split(/\r|\n/)[0];
    };

    this.export = function () {
        return {
            id: self.id,
            source: self.source
        };
    };
    this.import = function (data) {
        self.id = data.id;
        self.source = data.source;
    };
}

function KB() {
    var self = this;

    this.source = ko.observable('');
    this.articles = ko.observableArray();
    this.tags = ko.observableArray(['JSON', 'Javascript', 'Markdown', 'CSS', 'HTML']);
    this.focus = ko.observable();

    this.getArticles = function () {
        Services.local({
            method: 'get-articles',
            complete: function (data) {
                if (data) {
                    var articles = [];
                    for (var i = 0; i < data.length; i++) {
                        var article=new Article();
                        article.import(data[i]);
                        articles.push(article);
                    }
                    self.focus(null);
                    self.articles(articles);
                }
            }
        });
    };

    this.save = function (item, e) {
        var article = new Article(self.source());
        Services.local({
            method: 'save-article',
            params: article,
            complete: function (data) {
                if (data) {
                    article.id = data;
                    self.articles.unshift(article);
                    self.focus(article);
                    self.source('');
                }
            }
        });
    };
    this.select = function (item) {
        self.focus(item);
    };
}

$(document).ready(function () {
    var kb = new KB();
    ko.applyBindings(kb);

    kb.getArticles();
});